#include "contactsrequest.h"

ContactsRequest::ContactsRequest(QObject *parent)
    : ExecutionObjectInterface(parent)
{
    urlPath_ = "http://pcw-textinclass.appspot.com/getContacts";

    cookieData_ = "";

    manager_ = NULL;
}

ContactsRequest::ContactsRequest(QString cookieData, QObject *parent)
    : ExecutionObjectInterface(parent)
{
    urlPath_ = "http://pcw-textinclass.appspot.com/getContacts";

    cookieData_ = cookieData;

    manager_ = NULL;
}

ContactsRequest::~ContactsRequest()
{

}

void ContactsRequest::doInBackground()
{
    manager_ = new QNetworkAccessManager(this);

    if (manager_ == NULL) {
        emit error("Unable to allocate Network Access Manager");
        emit processFinished();
        return;
    }

    QUrl url(urlPath_);
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    request.setRawHeader(tr("Cookie").toUtf8(), cookieData_.toUtf8());

    connect(manager_, SIGNAL(finished(QNetworkReply*)), this, SLOT(onNetworkReply(QNetworkReply*)));

    manager_->get(request);
}

void ContactsRequest::onPostExecute()
{
    emit objectFinished();
}

void ContactsRequest::onNetworkReply(QNetworkReply *reply)
{
    QString responseString = reply->readAll();

    QDomDocument doc;
    QStringList names;
    QStringList numbers;

    if (!doc.setContent(responseString)) {
        emit error("Unable to parse XML");
    }
    else {
        QDomNodeList contactNodes = doc.elementsByTagName(tr("contact"));

        for (int i = 0; i < contactNodes.size(); i++) {
            QDomNode contact = contactNodes.item(i);

            QDomNodeList nameAndNumber = contact.childNodes();

            if (nameAndNumber.size() == 2) {
                names.append(nameAndNumber.at(0).firstChild().toText().data());
                numbers.append(nameAndNumber.at(1).firstChild().toText().data());
            }
        }

        emit responseStrings(names, numbers);
    }

    emit processFinished();
}
